import base64
import random
import re
import string
import sys

from django.contrib.auth import authenticate, logout, login
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render, redirect

from account.models import User
from static.help.code import send
from static.help.img_cre import GetRandomImgName
from static.help.user_cre import GetRandomUserName


# Create your views here.
def getCode(request):
    to_addr = request.GET.get('addr')
    codes = string.digits + string.ascii_letters
    code_ = ''.join(random.choices(codes, k=4))
    status = send(to_addr, code_)
    out = {
        "status": f'{status}',
    }
    if status:
        obj = JsonResponse(out)
        request.session['code'] = code_
        return obj
    else:
        out['error'] = '验证码获取失败！'
        obj = JsonResponse(out)
        return obj


def addUser(request):
    code_in = request.POST.get('code_in', '0')
    out = {}
    code = request.session.pop('code') if 'code' in request.session else '1'
    if code_in.lower() == code.lower():
        try:
            image = request.POST.get('img')
            profile = 'static/media/default/user.jpg'
            if image:
                imageinfo = image.split(',')[0]
                obj = re.compile(r'/(.*?);')
                imageType = obj.search(imageinfo).group(1)
                base64image = image.split(',')[1]
                imagedata = base64.b64decode(base64image)
                imgname = GetRandomImgName()
                with open(f'./static/media/upload/{imgname}.{imageType}', 'ab') as fp:
                    fp.write(imagedata)
                profile = f'static/media/upload/{imgname}.{imageType}'
            user = User.objects.create_user(
                username=GetRandomUserName(),
                email=request.POST.get('tag_in'),
                password=request.POST.get('pwd'),
                profile = profile,
            )

            user.save()
            out['status'] = 'true'

        except Exception as e:
            return render(request,'500.html',{'error':e})
        #     out['error'] = '邮箱已被注册！'
        #     out['status'] = 'false'
    else:
        out['error'] = '验证码填写错误！'
        out['status'] = 'false'
    return JsonResponse(out)


def wait(request):
    return render(request, '3s.html')


def login_(request):
    return render(request, 'login.html')


def accountCheck(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        pwd = request.POST.get('pwd')
        is_allowed = request.POST.get('allow')
        user = authenticate(email=email, password=pwd)
        if user:
            login(request, user)
            # 如果记住登陆，则使用全局的过期时间，默认为2周
            request.session['UserId'] = request.user.id
            if is_allowed:
                # 设置为None，则表示使用全局的过期时间
                request.session.set_expiry(60*30)
            else:
                # 否则设为0，关掉浏览器就注销登陆状态了
                request.session.set_expiry(0)

            next_url = request.GET.get('next')
            if next_url:
                return redirect(next_url)
            return redirect('/')
    return render(request, '3s.html')


@login_required(login_url='/account/login/')
def logout_(request):
    logout(request)
    return redirect('/')


def index(request):
    return render(request, 'space.html')


def page_error(request):
    error = sys.exc_info()
    context = {
        'error': error
    }
    return render(request, '500.html', context=context)